/**
 * Simple class for handling global events according the publish/subscribe
 * paradigm.
 *
 * Note: for every subscribe() there should an unsubscribe()!
 *
 * The events are JS objects having only one required parameter, 'name'. Example
 * of a valid event:
 *   { 'name': 'login', 'params': { 'uid': 123 } }
 *
 * The event names should be unique across the application or there might happen
 * some weird things.
 */
var EventManager = {
    subscribers: [],

    /**
     * Note: the callback can not be an anonymous function!
     */
    subscribe: function(eventName, callback, context) {
        util.log("{EventManager.subscribe} start");
        this.subscribers.push({
            eventName: eventName,
            callback: callback,
            context: context
        });
    },

    unsubscribe: function(eventName, callback, context) {
        util.log("{EventManager.unsubscribe} start");
        // Let's reverse so that we can do this with just one pass and without
        // any temporary arrays
        for(var i = this.subscribers.length - 1; i >= 0; i--) {
            var s = this.subscribers[i];

            if(s.eventName === eventName &&
               s.callback === callback &&
               s.context === context) {
               this.subscribers.splice(i, 1);
            }
        }
    },

    publish: function(event) {
        util.log("{EventManager.publish} start");
        if(!event || !event.name) {
            return false;
        }

        for(var i = 0, len = this.subscribers.length; i < len; i++) {
            var s = this.subscribers[i];
            
			if(s == undefined) {
                util.log("Event handler problem, subscriber "+i+" missing for ["+event.name+"]");
                continue;
            }
			
            if(s.eventName === event.name) {
                s.callback.call(s.context, event);
            }
        }

        return true;
    }
}